package com.qnbc.mystery.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.qnbc.mystery.config.AliPayConfig;
import com.qnbc.mystery.core.controller.BaseController;
import com.qnbc.mystery.core.domain.AjaxResult;
import com.qnbc.mystery.core.page.TableDataInfo;
import com.qnbc.mystery.core.utils.poi.ExcelUtil;
import com.qnbc.mystery.pojo.domain.FoodOrder;
import com.qnbc.mystery.pojo.domain.OrderDetail;
import com.qnbc.mystery.pojo.domain.User;
import com.qnbc.mystery.service.IFoodOrderService;
import com.qnbc.mystery.service.IOrderDetailService;
import com.qnbc.mystery.utils.DateUtils;
import com.qnbc.mystery.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 小程序订单
 *
 * @author guzj
 * @date 2023-12-27
 */
@Api("下单模块")
@RestController
@RequestMapping("/my/order")
public class AppletOrderController extends BaseController {
    @Autowired
    private IFoodOrderService orderService;

    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private IOrderDetailService orderDetailService;


    //更新订单状态
    @PostMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody FoodOrder order) {
        FoodOrder resultOrder = orderService.getById(order.getId());
        resultOrder.setStatus(order.getStatus());
        boolean b = orderService.saveOrUpdate(resultOrder);
        if (b) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    //创建订单 返回订单号
    @ApiOperation("创建订单")
    @PostMapping("/create")
    @Transactional
    public AjaxResult create(@RequestBody FoodOrder order) {
        order.setCreatedTime(new Date());
        order.setUpdatedTime(new Date());
        User currentUser = TokenUtils.getCurrentUser();
        order.setCreatedBy(String.valueOf(currentUser.getId()));
        order.setOrderNo(DateUtils.getCurrentDateStr());//订单id格式用DateUtil
        order.setCreatedTime(new Date());//添加创建日期属性
        order.setStatus(2);//添加创建日期属性

        boolean save = orderService.save(order);//添加订单到数据库
        if (save) {
            List<OrderDetail> goods = order.getGoods();//获取商品详情
            //遍历goods，添加订单详情到数据库
            for (OrderDetail orderDetail : goods) {
                orderDetail.setMid(order.getId());
                orderDetailService.save(orderDetail);
            }
        }
        //获取所需的订单号
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("orderNo", order.getId());
        //todo  支付
        return AjaxResult.success(resultMap);
    }

    /**
     * 查询订单管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FoodOrder order) {
        startPage();
        User currentUser = TokenUtils.getCurrentUser();
        order.setCreatedBy(String.valueOf(currentUser.getId()));
        List<FoodOrder> list = orderService.selectFoodOrderList(order);
        return getDataTable(list);
    }

    /**
     * 导出订单管理列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, FoodOrder order) {
        List<FoodOrder> list = orderService.selectFoodOrderList(order);
        ExcelUtil<FoodOrder> util = new ExcelUtil<FoodOrder>(FoodOrder.class);
        util.exportExcel(response, list, "订单管理数据");
    }

    /**
     * 获取订单管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(orderService.selectOrderById(id));
    }

    /**
     * 新增订单管理
     */
    @PostMapping
    public AjaxResult add(@RequestBody FoodOrder order) {
        return toAjax(orderService.insertFoodOrder(order));
    }

    /**
     * 修改订单管理
     */
    @PutMapping
    public AjaxResult edit(@RequestBody FoodOrder order) {
        return toAjax(orderService.updateFoodOrder(order));
    }

    /**
     * 删除订单管理
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(orderService.deleteFoodOrderByIds(ids));
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            // 支付宝验签
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8");
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 更新订单未已支付
                FoodOrder FoodorderInfo = orderService.selectOrderById(Long.valueOf(tradeNo));
                FoodorderInfo.setAlipayTraceNo(alipayTradeNo);
                FoodorderInfo.setStatus(2);
                orderService.updateById(FoodorderInfo);
            }
        }
        return "success";
    }
}
